import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;


public class DownloadFile {
	boolean debug = false;
	private String shaValue;
	private FileObject fileObject;
	private String currentDir;

	private ChunkElement[] chunks;
	private long chunksLength=0;
	private long chunksReceived=0;
	
	public DownloadFile(String shaValue, FileObject fo, String currentDir){
		this.shaValue = shaValue;
		this.fileObject = fo;
		this.currentDir = currentDir;

		chunks = new ChunkElement[fileObject.nchunks];
		if (debug) System.out.println("NChunks : " + fileObject.nchunks);
		if (debug) System.out.println("Chunks size: " + chunks.length); 
		System.out.println(); 
	}
	
	public String getShaValue(){
		return shaValue;
	}
	
	public FileObject getFileObject(){
		return fileObject;
	}
	
	public ChunkElement[] getChunks(){
		return chunks;
	}
	
	public void createFile() throws IOException
	{
		File file = new File(currentDir + "/Files/" + fileObject.filename);
		fileObject.setFile(file);
		file.createNewFile();
		RandomAccessFile raf = new RandomAccessFile(file, "rw");
		int i=0;
		while(i<chunks.length){
			long offset = i*1024;
			raf.seek(offset);
			raf.write(chunks[i].getChunk());
			i++;
		}
		raf.close();
		System.out.println("* The file " + fileObject.filename+ " is complete.");
	}
	
	public boolean allChunksReceived(){
		return (chunksLength == chunks.length);
	}
	
	public void addChunk(ChunkElement chunk){
		int chunkN = (int)chunk.getIndex();
		if(chunksReceived != -1)
			chunksReceived++;
		if(this.chunks[chunkN] == null)
		{
			this.chunks[chunkN] = chunk;
			chunksLength++;
			if (debug) System.out.println("Chunks[] Real Length: " + chunksLength);
		}
	}
	
	public long chunksReceived(){
		return chunksReceived;
	}
	
	public void setChunksReceived(long n){
		chunksReceived = n;
	}
	
}
